import { UiButton } from "@/shared/Uikit/UiButton";
import { UiSelectField } from "@/shared/Uikit/UiSelectField"; // Likely not used here
import { UiTextField } from "@/shared/Uikit/UiTextField";
import { useGetCurrentUser } from "@/entities/user/model/useGetCurrentUser"; // Likely not used here
import { useEffect, useRef, useState } from "react";
import { useCreateTest } from "../model/useCreateTest";
import { ClassNames } from "@emotion/react";
import clsx from "clsx";
import { ITest } from "@/shared/interfaces";

type ITestQuestion = {
    question: string;
    choices: string[];
};

export default function CreateTestForm(props: { onSuccess?: (response: ITest) => void }) {
    const [questions, setQuestions] = useState<ITestQuestion[]>([]);
    const [answers, setAnswers] = useState<Record<string, string>>({}); // Map question to true answer
    const [needAnswers, setNeedAnswers] = useState(0);
    const { handleMutate, isSuccess, errorMessage, response } = useCreateTest();

    useEffect(() => {
        if (isSuccess && props.onSuccess && response) {
            props.onSuccess(response);
        }
    }, [isSuccess]);

    const handleAddQuestion = () => {
        setQuestions([...questions, { question: '', choices: [] }]);
    };

    const handleAddChoice = (questionIndex: number) => {
        setQuestions(
            questions.map((question, idx) =>
                idx === questionIndex ? { ...question, choices: question.choices.concat('') } : question
            )
        );
    };

    const handleQuestionChange = (question: string, questionIndex: number) => {
        setQuestions(
            questions.map((q, idx) => (idx === questionIndex ? { ...q, question } : q))
        );
    };

    const handleChoiceChange = (choice: string, choiceIndex: number, questionIndex: number) => {
        setQuestions(
            questions.map((q, idx) =>
                idx === questionIndex
                    ? { ...q, choices: q.choices.map((c, i) => (i === choiceIndex ? choice : c)) }
                    : q
            )
        );
    };

    const handleChoiceSelect = (choice: string, questionIndex: number) => {
        setAnswers({ ...answers, [questions[questionIndex].question]: choice });
    };

    const handleDeleteQuestion = (questionIndex: number) => {
        setQuestions(questions.filter((_, idx) => idx !== questionIndex));
    };

    const handleDeleteChoice = (choiceIndex: number, questionIndex: number) => {
        const updatedChoices = questions[questionIndex].choices.filter((_, idx) => idx !== choiceIndex);
        setQuestions(
            questions.map((q, idx) => (idx === questionIndex ? { ...q, choices: updatedChoices } : q))
        );
    };

    const handleSubmit = () => {
        const test = {
            needTrueAnswers: needAnswers,
            questions: questions.map((question) => ({
                question: question.question,
                choices: question.choices,
            })),
            answers: questions.map((question) => ({
                question: question.question,
                answer: answers[question.question],
            })),
        };
        handleMutate(test);
    };

    return (
        <div className={clsx("flex h-[90vh] flex-col gap-4 overflow-scroll", {
            "bg-gray-100": true, // Tailwind CSS background color
            "p-4": true, // Tailwind CSS padding
        })}>
            <h1 className="font-bold text-2xl text-gray-800">Создание теста</h1>
            <UiTextField
                label="Количество необходимых ответов"
                inputProps={{
                    type: 'number',
                    value: needAnswers,
                    onChange: (e) => setNeedAnswers(+e.target.value),
                }}
                className={clsx("mb-4", {
                    "border-gray-300": true, // Tailwind CSS border color
                    "focus:border-blue-500 focus:ring-blue-500": true, // Tailwind CSS focus styles
                })}
            />
            <div className="flex flex-col gap-4">
                {questions.map((question, questionIndex) => (
                    <div
                        key={questionIndex}
                        className={clsx("flex flex-col rounded-md border border-gray-200 p-4", {
                            "bg-white": true, // Tailwind CSS background color
                        })}
                    >
                        <UiTextField
                            key={questionIndex}
                            label="Вопрос"
                            inputProps={{
                                placeholder: "Введите вопрос",
                                value: question.question,
                                onChange: (e) => handleQuestionChange(e.target.value, questionIndex),
                            }}
                            className={clsx("mb-4", {
                                "border-gray-300": true, // Tailwind CSS border color
                                "focus:border-blue-500 focus:ring-blue-500": true, // Tailwind CSS focus styles
                            })}
                        />
                        <ul>
                            {question.choices.map((choice, choiceIndex) => {
                                const isSelected = question.question && answers[question.question] === choice;
                                return (
                                    <li
                                        key={`${choiceIndex},${questionIndex}`}
                                        className={clsx(
                                            "flex justify-between items-center mt-2 p-2 rounded-md cursor-pointer hover:bg-gray-100",
                                            {
                                                "bg-gray-300": isSelected, // Tailwind CSS background color for selected choice
                                            }
                                        )}
                                    >
                                        <div className="flex items-center">
                                            <input
                                                key={`${choiceIndex},${questionIndex}`}
                                                type="checkbox"
                                                checked={!!isSelected}
                                                onChange={() => handleChoiceSelect(choice, questionIndex)}
                                                className={clsx("mr-2", {
                                                    "focus:ring-blue-500": true, // Tailwind CSS focus ring
                                                })}
                                            />
                                            <UiTextField
                                                key={choiceIndex}
                                                inputProps={{
                                                    value: choice,
                                                    onChange: (e) => handleChoiceChange(e.target.value, choiceIndex, questionIndex)
                                                }}
                                                className={clsx("w-full", {
                                                    "border-gray-300": true, // Tailwind CSS border color
                                                    "focus:border-blue-500 focus:ring-blue-500": true, // Tailwind CSS focus styles
                                                })}
                                            />
                                        </div>
                                        <UiButton
                                            variant="secondary"
                                            onClick={() => handleDeleteChoice(choiceIndex, questionIndex)}
                                            className={clsx({
                                                "text-red-500 hover:text-red-700": true, // Tailwind CSS colors for delete button
                                            })}
                                        >-</UiButton>
                                    </li>
                                );
                            })}
                        </ul>
                        <div className="flex justify-end">
                            <UiButton
                                variant="secondary"
                                onClick={() => handleAddChoice(questionIndex)}
                                className={clsx({
                                    "mr-2": true, // Tailwind CSS margin for spacing
                                    "text-green-500 hover:text-green-700": true, // Tailwind CSS colors for add choice button
                                })}
                            >+</UiButton>
                            <UiButton
                                variant="secondary"
                                onClick={() => handleDeleteQuestion(questionIndex)}
                                className={clsx({
                                    "text-red-500 hover:text-red-700": true, // Tailwind CSS colors for delete question button
                                })}
                            >-</UiButton>
                        </div>
                    </div>
                ))}
                <UiButton variant="secondary" onClick={handleAddQuestion}>
                    Добавить вопрос
                </UiButton>
            </div>
            <UiButton variant="primary" onClick={handleSubmit} disabled={!questions.length}>
                Сохранить тест
            </UiButton>
            {errorMessage && <div className="text-red-500">{errorMessage}</div>}
            {isSuccess && <>Успешно</>}
        </div>
    );
}